package com.FOD.clases;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.FOD.adapter.ScheduleAdapter;
import com.FOD.entities.Cita;
import com.FOD.entities.User;
import com.FOD.util.SessionDBHandler;
import com.FOD.web.DatesFunctions;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;

public class DateSchedule extends Activity {

	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";

	private Calendar today;
	private TextView month;
	private TextView year;
	private TextView day;
	private ListView schedule;
	private ScheduleAdapter adapter;
	ProgressDialog pDialog;
	private int userType;

	private ArrayList<Cita> dateList;
	private ArrayList<User> userList;

	private ArrayList<String> dates;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.date_schedule);

		SessionDBHandler db = new SessionDBHandler(getApplicationContext());
		userType = db.getUserType();
		db.close();

		dateList = new ArrayList<Cita>();
		userList = new ArrayList<User>();

		int yearInt = getIntent().getExtras().getInt("year");
		int dayInt = getIntent().getExtras().getInt("day");
		int monthInt = getIntent().getExtras().getInt("month");

		today = new GregorianCalendar();
		today.set(yearInt, monthInt, dayInt);

		month = (TextView) findViewById(R.id.MonthSchedule);
		year = (TextView) findViewById(R.id.YearSchedule);
		day = (TextView) findViewById(R.id.DaySchedule);

		month.setText(getIntent().getStringExtra("monthString"));
		year.setText("" + yearInt);
		day.setText((dayInt / 10) > 0 ? "" + dayInt : "0" + dayInt);

		schedule = (ListView) findViewById(R.id.ScheduleList);
		adapter = new ScheduleAdapter(this, today);

		dates = new ArrayList<String>();

		new GetDates().execute();

	}

	private ArrayList<String> getDates() {
		dates.clear();

		for (Cita cita : dateList) {
			dates.add(cita.getHorario());
		}

		return dates;
	}

	private void getDatesFromServer() {
		DatesFunctions datesFunctions = new DatesFunctions();
		// Creamos un JSON y le asignamos el json que regresa la conexion al
		// servidor
		JSONObject json = datesFunctions.getDates(today.getTime());
		dateList = new ArrayList<Cita>();

		// Verificamos la respuesta del servidor en el JSON
		try {
			// SI el tag no viene null
			if (json.getString(KEY_SUCCESS) != null) {
				String res = json.getString(KEY_SUCCESS);

				if (Integer.parseInt(res) == 1) {
					JSONObject list = json.getJSONObject("list");
					JSONArray jsonDates = list.getJSONArray("dates");

					for (int i = 0; i < jsonDates.length(); i++) {

						JSONObject catObj = (JSONObject) jsonDates.get(i);
						Cita cita = new Cita();
						cita.setId(catObj.getInt("id"));
						SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat(
								"yyyy-MM-dd");
						Date d1 = dateFormatOfStringInDB.parse(catObj
								.getString("fecha_consulta"));
						cita.setFecha_consulta(d1);
						cita.setHorario(catObj.getString("horario"));
						cita.setEmpleado_id(catObj.getInt("empleado_id"));
						d1 = dateFormatOfStringInDB.parse(catObj
								.getString("fecha_solicitud"));
						cita.setFecha_solicitud(d1);
						cita.setEstado(catObj.getInt("estado"));
						cita.setPaciente_id(catObj.getInt("paciente_id"));
						cita.setAceptada(catObj.getInt("aceptada") == 0 ? false
								: true);
						dateList.add(cita);
					}
					Log.w("DATE", "Citas obtenidas correctamente");
				} else {
					Log.e("DATE", "No se recivieron datos del servidor");
				}

			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.w("DATE", "Esta exepcion");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getDatesDoctorFromServer() {
		DatesFunctions datesFunctions = new DatesFunctions();
		// Creamos un JSON y le asignamos el json que regresa la conexion al
		// servidor
		JSONObject json = datesFunctions.getDatesDoctor(today.getTime());
		dateList = new ArrayList<Cita>();
		userList = new ArrayList<User>();

		// Verificamos la respuesta del servidor en el JSON
		try {
			// SI el tag no viene null
			if (json.getString(KEY_SUCCESS) != null) {
				String res = json.getString(KEY_SUCCESS);

				if (Integer.parseInt(res) == 1) {
					JSONObject list = json.getJSONObject("list");
					JSONArray jsonDates = list.getJSONArray("dates");

					for (int i = 0; i < jsonDates.length(); i++) {

						JSONObject catObj = (JSONObject) jsonDates.get(i);
						Cita cita = new Cita();

						cita.setId(catObj.getInt("id_cita"));
						SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat(
								"yyyy-MM-dd");
						Date d1 = dateFormatOfStringInDB.parse(catObj
								.getString("fecha_consulta"));
						cita.setFecha_consulta(d1);
						cita.setHorario(catObj.getString("horario"));
						cita.setEmpleado_id(catObj.getInt("empleado_id"));
						d1 = dateFormatOfStringInDB.parse(catObj
								.getString("fecha_solicitud"));
						cita.setFecha_solicitud(d1);
						cita.setEstado(catObj.getInt("estado"));
						cita.setPaciente_id(catObj.getInt("paciente_id"));
						cita.setAceptada(catObj.getInt("aceptada") == 0 ? false
								: true);
						Log.w("Citas que vienen", "" + cita);
						dateList.add(cita);

						User user = new User();

						user.setId(catObj.getInt("id"));
						user.setNickname(catObj.getString("nickname"));
						user.setPassword(catObj.getString("password"));
						user.setName(catObj.getString("name"));
						user.setMail(catObj.getString("mail"));
						user.setType(catObj.getInt("user_type"));
						user.setAge(catObj.getInt("age"));
						user.setSex(catObj.getInt("sex"));
						user.setDependecy(catObj.getString("dependency"));
						user.setSport(catObj.getString("sport"));
						user.setPhone(Long.valueOf((catObj.getInt("phone"))));
						d1 = dateFormatOfStringInDB.parse(catObj
								.getString("create_date"));
						user.setCreateDate(d1);
						Log.w("Usuarios que vienen", "" + user);
						userList.add(user);
					}

					Log.w("DATE", "Citas obtenidas correctamente");
				} else {
					Log.e("DATE", "No se recivieron datos del servidor");
				}

			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.w("DATE", "Esta exepcion");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Cargamos el layout que represente al menu correspondiente
		getMenuInflater().inflate(R.menu.date_schedule, menu);
		return true;
	}

	private class GetDates extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DateSchedule.this);
			pDialog.setMessage("Obteniendo citas..");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			switch (userType) {
			case 1:
				getDatesDoctorFromServer();
				break;

			case 2:
				break;
			case 3:
				getDatesFromServer();
				break;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing()) {
				pDialog.dismiss();
			}
			switch (userType) {
			case 1:
				adapter.setDates(getDates(), dateList, userList, userType);
				schedule.setAdapter(adapter);
				break;

			case 2:
				break;
			case 3:
				adapter.setDates(getDates(), dateList, userType);
				schedule.setAdapter(adapter);
				break;
			}
			adapter.setDates(getDates(), dateList, userType);
			schedule.setAdapter(adapter);
			// populateSpinner();
		}
	}
}
